<?php

namespace app\order\logic;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class OrderbalanceLogic
{
    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $payout_status = $params['payout_status'] ?? "";
        $shop_id = $params['shop_id'] ?? 0;
        $createtime = $params['createtime'] ?? "";
        $processed_at = $params['processed_at'] ?? "";
        $source_order_id = $params['source_order_id'] ?? 0;
        $payment_gateway_names = $params['payment_gateway_names'] ?? "";

        $where = [];

        if (!empty($createtime)) {
            $where[] = ['createtime', '>=', strtotime($createtime['0'])];
            $where[] = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        }
        if (!empty($processed_at)) {
            $where[] = ['processed_at', '>=', $processed_at['0']];
            $where[] = ['processed_at', '<=', date('Y-m-d',strtotime($processed_at['1']) + 3600*24)];
        }
        
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }
        if(!empty($payout_status)){
            $where[] = ['payout_status', '=', $payout_status];
        }
        if(!empty($payment_gateway_names)){
            $where[] = ['payment_gateway_names', '=', $payment_gateway_names];
        }
        if(!empty($source_order_id)){
            $where[] = ['source_order_id', 'like', '%' . $source_order_id . '%'];
        }

        $list = Db::name('order_balance_api')
            ->where($where)
            ->order('processed_at desc')
            ->paginate($limit);
        $lists = $list->items();
        
        $spends = Db::name('order_balance_api')
            ->field('SUM(amount) as amount,payout_status')
            ->where($where)
            ->group('payout_status')
            ->order('amount desc')
            ->select()->toarray();

        $spends_Total = 0;
        foreach ($spends as &$v) {
            $v['amount'] = getRes($v['amount']);
            $spends_Total += $v['amount'];
        }

        $spends_gateway = Db::name('order_balance_api')
            ->field('SUM(amount) as amount,payment_gateway_names')
            ->where('source_order_id',"<>","")
            ->where($where)
            ->group('payment_gateway_names')
            ->order('amount desc')
            ->select()->toarray();
        // halt($spends_gateway);
            
        $spends_gateway_Total = 0;
        foreach ($spends_gateway as &$v) {
            if(empty($v['payment_gateway_names'])){
                $v['payment_gateway_names'] = "未知";
            }
            $v['amount'] = getRes($v['amount']);
            $spends_gateway_Total += $v['amount'];
        }
        
        $data = [
            'list' => $lists,
            'total' => $list->total(),
            'spends' => $spends,
            'spends_Total' => getRes($spends_Total),
            'spends_gateway' => $spends_gateway,
            'spends_gateway_Total' => getRes($spends_gateway_Total),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['类型', 'type'];
        $header[] = ['状态', 'payout_status'];
        $header[] = ['金额', 'amount'];
        $header[] = ['订单ID', 'source_order_id'];
        $header[] = ['交易时间', 'processed_at'];
        $header[] = ['订单时间', 'created_at'];

        $tableName = "Orderbalance";

        $payout_status = $params['payout_status'] ?? "";
        $shop_id = $params['shop_id'] ?? 0;
        $createtime = $params['createtime'] ?? "";
        $processed_at = $params['processed_at'] ?? "";
        $source_order_id = $params['source_order_id'] ?? 0;

        $where = [];

        if (!empty($createtime)) {
            $where[] = ['createtime', '>=', strtotime($createtime['0'])];
            $where[] = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        }
        if (!empty($processed_at)) {
            $where[] = ['processed_at', '>=', $processed_at['0']];
            $where[] = ['processed_at', '<=', date('Y-m-d',strtotime($processed_at['1']) + 3600*24)];
        }
        
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }
        if(!empty($payout_status)){
            $where[] = ['payout_status', '=', $payout_status];
        }
        if(!empty($source_order_id)){
            $where[] = ['source_order_id', 'like', '%' . $source_order_id . '%'];
        }

        $count = Db::name('order_balance_api')
            ->where($where)
            ->count();
        if($count >= 5000){
            return '数据超过5000条,异步下载中，请2分钟后前往【任务组管理/系统导出管理】页面下载';
        }

        $lists = Db::name('order_balance_api')
            ->where($where)
            ->order('processed_at desc')
            ->select()->toarray();

        foreach ($lists as &$v) {
            $v['source_order_id'] = '订单ID:'.$v['source_order_id'];
        }
        
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

}
